package com.gqz.aircraftwar.util

import android.annotation.SuppressLint
import android.content.Context
import android.content.SharedPreferences
import com.gqz.aircraftwar.App
import java.lang.IllegalArgumentException
import kotlin.reflect.KProperty


/**
 * Descraption
 *
 * @author gqz
 * @data 2020/3/20
 */

class Preference(fileName: String) {

    var fileName: String = "Player"

    init {
        this.fileName = fileName
    }

    val sp by lazy {
        App.instance.applicationContext.getSharedPreferences(
            this.fileName,
            Context.MODE_PRIVATE
        )
    }

    fun <T> put(name: String, value: T) {
        val edit = sp.edit()
        when (value) {
            is Long -> edit.putLong(name, value)
            is String -> edit.putString(name, value)
            is Int -> edit.putInt(name, value)
            is Boolean -> edit.putBoolean(name, value)
            is Float -> edit.putFloat(name, value)
            else -> throw IllegalArgumentException("SharedPreferences can't save this type")
        }.apply()
    }

    fun <T> get(name: String, default: T): T {
        val ret: Any = when (default) {
            is Long -> sp.getLong(name, default)
            is String -> sp.getString(name, default)
            is Int -> sp.getInt(name, default)
            is Boolean -> sp.getBoolean(name, default)
            is Float -> sp.getFloat(name, default)
            else -> throw IllegalArgumentException("SharedPreferences can't get this type")
        }
        return ret as T
    }
}
